<template>
  <div>
    <el-tag
      :key="tag"
      v-for="tag in dynamicTags"
      closable
      size="small"
      :disable-transitions="false"
      @close="handleClose(tag)"
    >{{tag}}</el-tag>
    <el-popover v-if="inputVisible" placement="top" width="230" v-model="visible">
      <i class="el-icon-error"></i>该值已经存在，请重新输入！
      <div style="text-align: center; margin: 6px 0 -3px 0; padding: 0;">
        <el-button style="padding: 2px;" size="mini" type="text" @click="onCancel">取消</el-button>
        <el-button style="padding: 2px;" type="primary" size="mini" @click="onReset">确定</el-button>
      </div>
      <el-input
        slot="reference"
        class="input-new-tag"
        
        v-model="inputValue"
        ref="saveTagInput"
        size="mini"
        @keyup.enter.native="handleInputConfirm"
        @blur="handleInputConfirm"
      ></el-input>
    </el-popover>
    <el-button v-else class="button-new-tag" size="mini" @click="showInput">+ 属性值</el-button>
  </div>
</template>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 26px;
  line-height: 24px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>

<script>
export default {
  props: {
    value: {
      type: Array,
      default: function() {
        return [];
      }
    }
  },
  data() {
    return {
      visible:false,
      dynamicTags: this.$props.value,
      inputVisible: false,
      inputValue: ""
    };
  },
  watch: {
    value: function(nval) {
      this.dynamicTags = nval;
    }
  },
  methods: {
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      this.ReturnValue();
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        if (this.dynamicTags.indexOf(inputValue) >= 0) {//重复时提示
          this.visible=true;
          return;
        }
        this.dynamicTags.push(inputValue);
        this.ReturnValue();
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    onCancel(){//重复时取消添加
      this.visible = false;
      this.inputVisible = false;
      this.inputValue = "";
    },
    onReset(){//重复时继续修改后添加
      this.visible = false;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    ReturnValue() {
      this.$emit("change", this.dynamicTags); //返回值
      setTimeout(() => {
        this.$emit("set"); //可处理返回值
      }, 200); //延后至change处理完
    }
  }
};
</script>